<template>
  <div class="history-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">转换历史</h1>
          <p class="page-subtitle">管理您的所有转换任务</p>
        </div>
        
        <div class="header-actions">
          <!-- 批量操作 -->
          <div class="batch-actions" v-if="selectedTasks.length > 0">
            <span class="selected-count">已选择 {{ selectedTasks.length }} 项</span>
            <button 
              class="btn btn-secondary"
              @click="batchCancel"
              :disabled="!canBatchCancel"
            >
              批量取消
            </button>
            <button 
              class="btn btn-danger"
              @click="batchDelete"
            >
              批量删除
            </button>
          </div>
          
          <!-- 刷新按钮 -->
          <button 
            class="btn btn-primary"
            @click="refreshTasks"
            :disabled="loading"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="23,4 23,10 17,10"/>
              <polyline points="1,20 1,14 7,14"/>
              <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
            </svg>
            刷新
          </button>
        </div>
      </div>
    </div>
    
    <!-- 筛选和搜索 -->
    <div class="filters-section">
      <div class="filters-content">
        <!-- 状态筛选 -->
        <div class="filter-group">
          <label class="filter-label">状态筛选：</label>
          <div class="filter-buttons">
            <button 
              v-for="status in statusFilters"
              :key="status.value"
              class="filter-btn"
              :class="{ active: currentFilter === status.value }"
              @click="setFilter(status.value)"
            >
              <span class="filter-icon" :class="status.class"></span>
              {{ status.label }}
            </button>
          </div>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-group">
          <div class="search-input">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="11" cy="11" r="8"/>
              <path d="M21 21l-4.35-4.35"/>
            </svg>
            <input 
              type="text"
              placeholder="搜索文件名..."
              v-model="searchQuery"
              @input="handleSearch"
            />
            <button 
              v-if="searchQuery"
              class="clear-search"
              @click="clearSearch"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
          </div>
        </div>
        
        <!-- 排序选项 -->
        <div class="sort-group">
          <label class="filter-label">排序：</label>
          <select v-model="sortBy" @change="handleSort" class="sort-select">
            <option value="created_at">创建时间</option>
            <option value="updated_at">更新时间</option>
            <option value="filename">文件名</option>
            <option value="status">状态</option>
          </select>
          <button 
            class="sort-order-btn"
            @click="toggleSortOrder"
            :title="sortOrder === 'desc' ? '降序' : '升序'"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path v-if="sortOrder === 'desc'" d="M3 6l3 6l3-6"/>
              <path v-else d="M3 18l3-6l3 6"/>
              <path d="M21 6l-3 6l3 6"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 统计信息 -->
    <div class="stats-section" v-if="taskStats">
      <div class="stats-content">
        <div class="stat-card">
          <div class="stat-icon pending">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"/>
              <polyline points="12,6 12,12 16,14"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ taskStats.pending }}</div>
            <div class="stat-label">等待中</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon processing">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M21 12c0 4.97-4.03 9-9 9s-9-4.03-9-9 4.03-9 9-9c1.66 0 3.2.45 4.53 1.24"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ taskStats.processing }}</div>
            <div class="stat-label">处理中</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon completed">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="20,6 9,17 4,12"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ taskStats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon failed">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"/>
              <line x1="15" y1="9" x2="9" y2="15"/>
              <line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ taskStats.failed }}</div>
            <div class="stat-label">失败</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 任务列表 -->
    <div class="tasks-section">
      <div class="tasks-content">
        <!-- 全选控制 -->
        <div class="select-all-bar" v-if="filteredTasks.length > 0">
          <label class="checkbox-label">
            <input 
              type="checkbox"
              :checked="isAllSelected"
              :indeterminate="isPartiallySelected"
              @change="toggleSelectAll"
            />
            <span class="checkbox-custom"></span>
            全选 ({{ filteredTasks.length }} 项)
          </label>
          
          <div class="list-actions">
            <button 
              class="btn btn-sm btn-secondary"
              @click="exportTasks"
              :disabled="selectedTasks.length === 0"
            >
              导出选中
            </button>
          </div>
        </div>
        
        <!-- 任务列表组件 -->
        <TaskList 
          :tasks="filteredTasks"
          :loading="loading"
          :show-selection="true"
          :selected-tasks="selectedTasks"
          @task-selected="handleTaskSelection"
          @task-updated="handleTaskUpdated"
          @tasks-updated="refreshTasks"
        />
        
        <!-- 分页 -->
        <div class="pagination-section" v-if="totalPages > 1">
          <div class="pagination-info">
            显示 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, totalTasks) }} 
            共 {{ totalTasks }} 项
          </div>
          
          <div class="pagination-controls">
            <button 
              class="btn btn-sm"
              :disabled="currentPage <= 1"
              @click="goToPage(currentPage - 1)"
            >
              上一页
            </button>
            
            <div class="page-numbers">
              <button 
                v-for="page in visiblePages"
                :key="page"
                class="page-btn"
                :class="{ active: page === currentPage }"
                @click="goToPage(page)"
              >
                {{ page }}
              </button>
            </div>
            
            <button 
              class="btn btn-sm"
              :disabled="currentPage >= totalPages"
              @click="goToPage(currentPage + 1)"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useTaskStore } from '@/stores/task'
import TaskList from '@/components/TaskList.vue'
import type { Task } from '@/types/task'

// Store
const taskStore = useTaskStore()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const currentFilter = ref('all')
const sortBy = ref('created_at')
const sortOrder = ref<'asc' | 'desc'>('desc')
const selectedTasks = ref<string[]>([])
const currentPage = ref(1)
const pageSize = ref(20)

// 状态筛选选项
const statusFilters = [
  { value: 'all', label: '全部', class: '' },
  { value: 'pending', label: '等待中', class: 'pending' },
  { value: 'processing', label: '处理中', class: 'processing' },
  { value: 'completed', label: '已完成', class: 'completed' },
  { value: 'failed', label: '失败', class: 'failed' }
]

// 计算属性
const tasks = computed(() => taskStore.tasks)
const totalTasks = computed(() => taskStore.totalTasks)
const totalPages = computed(() => Math.ceil(totalTasks.value / pageSize.value))

const filteredTasks = computed(() => {
  let result = [...tasks.value]
  
  // 状态筛选
  if (currentFilter.value !== 'all') {
    result = result.filter(task => task.status === currentFilter.value)
  }
  
  // 搜索筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(task => 
      task.filename.toLowerCase().includes(query) ||
      task.original_filename.toLowerCase().includes(query)
    )
  }
  
  // 排序
  result.sort((a, b) => {
    let aValue = a[sortBy.value as keyof Task]
    let bValue = b[sortBy.value as keyof Task]
    
    if (typeof aValue === 'string') {
      aValue = aValue.toLowerCase()
    }
    if (typeof bValue === 'string') {
      bValue = bValue.toLowerCase()
    }
    
    if (sortOrder.value === 'desc') {
      return aValue > bValue ? -1 : aValue < bValue ? 1 : 0
    } else {
      return aValue < bValue ? -1 : aValue > bValue ? 1 : 0
    }
  })
  
  return result
})

const taskStats = computed(() => {
  const stats = { pending: 0, processing: 0, completed: 0, failed: 0 }
  tasks.value.forEach(task => {
    if (stats.hasOwnProperty(task.status)) {
      stats[task.status as keyof typeof stats]++
    }
  })
  return stats
})

const isAllSelected = computed(() => 
  filteredTasks.value.length > 0 && selectedTasks.value.length === filteredTasks.value.length
)

const isPartiallySelected = computed(() => 
  selectedTasks.value.length > 0 && selectedTasks.value.length < filteredTasks.value.length
)

const canBatchCancel = computed(() => 
  selectedTasks.value.some(taskId => {
    const task = tasks.value.find(t => t.id === taskId)
    return task && ['pending', 'processing'].includes(task.status)
  })
)

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const refreshTasks = async () => {
  loading.value = true
  try {
    await taskStore.fetchTasks({
      page: currentPage.value,
      limit: pageSize.value,
      status: currentFilter.value === 'all' ? undefined : currentFilter.value,
      search: searchQuery.value || undefined,
      sort_by: sortBy.value,
      sort_order: sortOrder.value
    })
  } catch (error) {
    console.error('Failed to refresh tasks:', error)
  } finally {
    loading.value = false
  }
}

const setFilter = (status: string) => {
  currentFilter.value = status
  currentPage.value = 1
  selectedTasks.value = []
  refreshTasks()
}

const handleSearch = () => {
  currentPage.value = 1
  selectedTasks.value = []
  refreshTasks()
}

const clearSearch = () => {
  searchQuery.value = ''
  handleSearch()
}

const handleSort = () => {
  currentPage.value = 1
  refreshTasks()
}

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
  handleSort()
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedTasks.value = []
  } else {
    selectedTasks.value = filteredTasks.value.map(task => task.id)
  }
}

const handleTaskSelection = (taskId: string, selected: boolean) => {
  if (selected) {
    if (!selectedTasks.value.includes(taskId)) {
      selectedTasks.value.push(taskId)
    }
  } else {
    const index = selectedTasks.value.indexOf(taskId)
    if (index > -1) {
      selectedTasks.value.splice(index, 1)
    }
  }
}

const handleTaskUpdated = () => {
  refreshTasks()
}

const batchCancel = async () => {
  if (!canBatchCancel.value) return
  
  try {
    await taskStore.batchCancelTasks(selectedTasks.value)
    selectedTasks.value = []
    refreshTasks()
  } catch (error) {
    console.error('Failed to batch cancel tasks:', error)
  }
}

const batchDelete = async () => {
  if (selectedTasks.value.length === 0) return
  
  if (!confirm(`确定要删除选中的 ${selectedTasks.value.length} 个任务吗？此操作不可撤销。`)) {
    return
  }
  
  try {
    await taskStore.batchDeleteTasks(selectedTasks.value)
    selectedTasks.value = []
    refreshTasks()
  } catch (error) {
    console.error('Failed to batch delete tasks:', error)
  }
}

const exportTasks = () => {
  if (selectedTasks.value.length === 0) return
  
  const selectedTaskData = filteredTasks.value.filter(task => 
    selectedTasks.value.includes(task.id)
  )
  
  const csvContent = [
    ['文件名', '状态', '输出格式', '创建时间', '完成时间'].join(','),
    ...selectedTaskData.map(task => [
      task.original_filename,
      task.status,
      task.output_format,
      new Date(task.created_at).toLocaleString(),
      task.completed_at ? new Date(task.completed_at).toLocaleString() : ''
    ].join(','))
  ].join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `tasks_export_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    refreshTasks()
  }
}

// 监听器
watch([currentPage, pageSize], () => {
  refreshTasks()
})

// 生命周期
onMounted(() => {
  refreshTasks()
})
</script>

<style scoped>
.history-view {
  min-height: 100vh;
  background: #f8fafc;
}

/* 页面头部 */
.page-header {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 2rem 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 0.5rem 0;
}

.page-subtitle {
  color: #64748b;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  background: #f1f5f9;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.selected-count {
  font-size: 0.875rem;
  color: #475569;
  font-weight: 500;
}

/* 筛选区域 */
.filters-section {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 1.5rem 0;
}

.filters-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  flex-wrap: wrap;
  gap: 2rem;
  align-items: center;
}

.filter-group,
.search-group,
.sort-group {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.filter-label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.filter-buttons {
  display: flex;
  gap: 0.5rem;
}

.filter-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.filter-btn.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.filter-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #9ca3af;
}

.filter-icon.pending { background: #f59e0b; }
.filter-icon.processing { background: #3b82f6; }
.filter-icon.completed { background: #10b981; }
.filter-icon.failed { background: #ef4444; }

.search-input {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input svg {
  position: absolute;
  left: 0.75rem;
  color: #9ca3af;
  pointer-events: none;
}

.search-input input {
  padding: 0.5rem 0.75rem 0.5rem 2.5rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.875rem;
  width: 250px;
  transition: all 0.2s ease;
}

.search-input input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.clear-search {
  position: absolute;
  right: 0.5rem;
  padding: 0.25rem;
  border: none;
  background: none;
  color: #9ca3af;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.clear-search:hover {
  color: #374151;
  background: #f3f4f6;
}

.sort-select {
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.875rem;
  background: white;
  cursor: pointer;
}

.sort-order-btn {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sort-order-btn:hover {
  background: #f9fafb;
}

/* 统计区域 */
.stats-section {
  padding: 1.5rem 0;
  background: #f8fafc;
}

.stats-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.pending { background: #f59e0b; }
.stat-icon.processing { background: #3b82f6; }
.stat-icon.completed { background: #10b981; }
.stat-icon.failed { background: #ef4444; }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 0.25rem;
}

.stat-label {
  font-size: 0.875rem;
  color: #64748b;
}

/* 任务区域 */
.tasks-section {
  flex: 1;
  padding: 2rem 0;
}

.tasks-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
}

.select-all-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px 8px 0 0;
  margin-bottom: -1px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 0.875rem;
  color: #374151;
}

.checkbox-label input[type="checkbox"] {
  display: none;
}

.checkbox-custom {
  width: 16px;
  height: 16px;
  border: 2px solid #d1d5db;
  border-radius: 3px;
  position: relative;
  transition: all 0.2s ease;
}

.checkbox-label input[type="checkbox"]:checked + .checkbox-custom {
  background: #3b82f6;
  border-color: #3b82f6;
}

.checkbox-label input[type="checkbox"]:checked + .checkbox-custom::after {
  content: '';
  position: absolute;
  left: 2px;
  top: -1px;
  width: 6px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-label input[type="checkbox"]:indeterminate + .checkbox-custom {
  background: #3b82f6;
  border-color: #3b82f6;
}

.checkbox-label input[type="checkbox"]:indeterminate + .checkbox-custom::after {
  content: '';
  position: absolute;
  left: 2px;
  top: 6px;
  width: 8px;
  height: 2px;
  background: white;
}

.list-actions {
  display: flex;
  gap: 0.5rem;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 0;
  margin-top: 2rem;
  border-top: 1px solid #e2e8f0;
}

.pagination-info {
  font-size: 0.875rem;
  color: #64748b;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.page-numbers {
  display: flex;
  gap: 0.25rem;
}

.page-btn {
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  font-size: 0.875rem;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.page-btn:hover {
  background: #f9fafb;
}

.page-btn.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: 1px solid transparent;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #4b5563;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #dc2626;
}

.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 0.8125rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .filters-content {
    flex-direction: column;
    align-items: stretch;
    gap: 1rem;
  }
  
  .filter-group,
  .search-group,
  .sort-group {
    flex-wrap: wrap;
  }
  
  .stats-content {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}

@media (max-width: 768px) {
  .page-header,
  .filters-section,
  .stats-section,
  .tasks-section {
    padding-left: 1rem;
    padding-right: 1rem;
  }
  
  .header-content,
  .filters-content,
  .stats-content,
  .tasks-content {
    padding-left: 0;
    padding-right: 0;
  }
  
  .search-input input {
    width: 200px;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 1rem;
  }
  
  .select-all-bar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
}

@media (max-width: 640px) {
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .filter-buttons {
    flex-wrap: wrap;
  }
  
  .search-input input {
    width: 100%;
  }
  
  .stats-content {
    grid-template-columns: 1fr;
  }
  
  .page-numbers {
    flex-wrap: wrap;
  }
}
</style>